<template>
	<view>
		<!-- <map
			class="map"
			:style="{ height: screenHeight }"
			:latitude="latitude"
			:longitude="longitude"
			:markers="markers"
			ref="map"
			show-compass="true"
			show-location="true"
			:circles="circles"
			:include-points="includePoints"
		></map> -->
		<!-- <image src="../../static/clockbg.jpg" mode=""></image> -->
		<view class="clockInfo">
			<view>
				<icon class=" iconfont iconziyuan"></icon>
				<text v-text="date"></text>
			</view>
			<view>
				<icon class=" iconfont iconziyuan1"></icon>
				<text v-text="addr"></text>
			</view>
		</view>
		<!-- 拍照功能 -->
		<view class="cameraBox">
			<image :src="userImg" mode="aspectFill"></image>
			<text v-text="watermark"></text>
		</view>
		<view class="cameraAction"><text @click="plusCamera" class="camera">拍照</text></view>
		<!-- 拍照功能 -->
		<view class="clockAction" :class="clockActive && watermark ? '' : 'clockGray'" @click="debounceClock('clockFun', 2000)">
			<text>{{ clockText }}</text>
			<text v-text="time"></text>
		</view>
		<commonToast v-if="clockSuccess" title="打卡成功!"></commonToast>
		<!-- <button bindtap="openSetting" class="authSettingBtn">打开设置页</button> -->
	</view>
</template>

<script>
import { format, screenHeight } from '@/libs/common.js';
import QQMapWX from '@/libs/qqmap/qqmap-wx-jssdk.js';
import common from '@/libs/login.js';
import baseUrl from '@/libs/config.js';
import commonToast from '@/wxcomponents/commonLayout/commonToast.vue';
export default {
	data() {
		return {
			timeout: null,
			flag: true,
			clockSuccess: false,
			date: '',
			time: '',
			title: 'map',
			latitude: '',
			longitude: '',
			markers: [],
			screenHeight: screenHeight + 'px',
			addr: '获取定位中...',
			circles: [
				{
					latitude: '',
					longitude: '',
					fillColor: '#3C68E550',
					radius: 0
				}
			],
			userPosi: {},
			includePoints: [],
			clockActive: false,
			setDistance: '',
			userImg: '',
			attachmentVoListStr: '',
			watermark: '',
			// 是否在打卡范围内
			inClockRange: true
		};
	},
	onLoad() {
		let that = this;
		this.date = format('YY-mm-dd', new Date());
		this.time = format('HH:MM:SS', new Date());
		setInterval(() => {
			this.date = format('YY-mm-dd', new Date());
			this.time = format('HH:MM:SS', new Date());
		}, 1000);
		this.$http
			.get({
				url: '/stu/studentAttendance/getSignConfig',
				data: ''
			})
			.then(async resp => {
				this.schoolLocation(resp.result.school_location, resp.result.location_distance);
				await this.userLocation();
				this.centerPointer(resp.result.location_distance);
				this.setDistance = resp.result.location_distance;
			});
	},
	methods: {
		openSetting() {
			let that = this
			uni.openSetting({
				//打开微信设置页面
				success(res) {
					if (res.authSetting['scope.userLocation']) {
						//再次判断是否授权
						uni.getLocation({
							success: res => {
								that.userPosi = res;
								qqmapsdk.reverseGeocoder({
									location: {
										latitude: res.latitude,
										longitude: res.longitude
									},
									success(res) {
										// that.addr = res.result.formatted_addresses.recommend;
										that.setAddr(res.result.formatted_addresses.recommend);
									}
								});
								resolve(res);
							}
						});
					} else {
						wx.showToast({
							title: '您拒绝了定位权限，将无法使用考勤打卡功能，请重新进入打卡页面进行授权！',
							icon: 'none'
						});
						that.addr = '定位获取失败';
					}
				}
			});
		},
		//拍照
		plusCamera() {
			let that = this;
			let Authorization = uni.getStorageSync('Authorization');
			let header = {
				Authorization: 'Wechat ' + Authorization
			};
			uni.chooseImage({
				count: 6, //默认9
				sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['camera'], //从相册选择
				success: function(res) {
					// console.log(JSON.stringify(res.tempFilePaths));
					that.userImg = res.tempFilePaths[0];
					uni.uploadFile({
						url: baseUrl + '/stu/common/uploadFile',
						filePath: res.tempFilePaths[0],
						name: 'file',
						header: header,
						success: uploadFileRes => {
							console.log(uploadFileRes);
							let data = JSON.parse(uploadFileRes.data);
							if (data.code == 0) {
								let res = data.result;
								let arr = [];
								arr.push({
									fileId: res.id,
									fileUrl: res.fileUrl,
									docFileId: res.id,
									docFileUrl: res.fileUrl,
									docFileName: res.fileName
								});

								that.attachmentVoListStr = JSON.stringify(arr);

								let weekDay;
								switch (new Date().getDay()) {
									case 0: {
										weekDay = '星期日';
										break;
									}
									case 1: {
										weekDay = '星期一';
										break;
									}
									case 2: {
										weekDay = '星期二';
										break;
									}
									case 3: {
										weekDay = '星期三';
										break;
									}
									case 4: {
										weekDay = '星期四';
										break;
									}
									case 5: {
										weekDay = '星期五';
										break;
									}
									case 6: {
										weekDay = '星期六';
										break;
									}
									default: {
										uni.showToast({
											icon: 'none',
											title: '出错了～'
										});
										// param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, ERROR_CONF.SYSTEM_ERR_MSG));
									}
								}
								that.watermark = `${format('YY-mm-dd HH:MM:SS', new Date())}  ${weekDay}`;
							}
						},
						fail(e) {
							uni.showToast({
								icon: 'none',
								title: '上传失败'
							});
						}
					});
				},
				fail(res) {
					uni.showToast({
						icon: 'none',
						title: JSON.stringify(res)
					});
				}
			});
		},
		//在地图上画圈圈，蓝色的
		schoolLocation(posi, distance) {
			let that = this;
			this.circles = posi.map(ele => {
				that.markers.push({
					id: that.markers.length + 1,
					latitude: ele.latitude,
					longitude: ele.longitude,
					iconPath: '/static/posi.png',
					width: 50,
					height: 50
				});
				return {
					latitude: ele.latitude,
					longitude: ele.longitude,
					fillColor: '#3C68E550',
					radius: distance
				};
			});
		},
		//获取用户定位信息
		userLocation() {
			let that = this;
			let qqmapsdk = new QQMapWX({
				key: 'AVVBZ-IOGH4-GI2UM-D3W7R-L3UNK-BNBZG'
			});
			return new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'gcj02',
					success(res) {
						that.userPosi = res;
						//转译坐标=>地理位置
						qqmapsdk.reverseGeocoder({
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success(res) {
								// that.addr = res.result.formatted_addresses.recommend;
								that.setAddr(res.result.formatted_addresses.recommend);
							},
							fail(res) {
								that.addr = '未获取到地理位置';
								wx.showToast({
									title: '获取地理位置失败，请到信号好的位置重试',
									icon: 'none'
								});
								that.clockActive = false;
							}
						});
						resolve(res);
					},
					async fail(res) {
						let scoped = await common.getSetting('scope.userLocation').catch(e => {
							return e;
						});
						if (!scoped) {
							//此时用户为授权地理位置
							uni.showToast({
								title: '请授权地理位置！',
								icon: 'none',
								success() {}
							});
							uni.showModal({
								title: '提示',
								content: '您拒绝了定位权限，将无法使用考勤打卡功能,是否重新授权？',
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											//打开微信设置页面
											success(res) {
												if (res.authSetting['scope.userLocation']) {
													//再次判断是否授权
													uni.getLocation({
														success: res => {
															that.userPosi = res;
															qqmapsdk.reverseGeocoder({
																location: {
																	latitude: res.latitude,
																	longitude: res.longitude
																},
																success(res) {
																	// that.addr = res.result.formatted_addresses.recommend;
																	that.setAddr(res.result.formatted_addresses.recommend)
																}
															});
															resolve(res);
														}
													});
												} else {
													wx.showToast({
														title: '您拒绝了定位权限，将无法使用考勤打卡功能，请重新进入打卡页面进行授权！',
														icon: 'none'
													});
													that.addr = '定位获取失败';
												}
											}
										});
									}
								}
							});
						}
					}
				});
			});
		},
		//确定地图的中心点，取打卡地点距离用户定位的中间位置
		centerPointer(locationDistance) {
			let that = this;
			let distance = [];
			let min = '';
			let i = '';
			//计算目标点与定位的距离
			this.markers.forEach((ele, index) => {
				let s = that.calPointerDistance(ele, that.userPosi);
				distance.push(s);
			});
			min = Math.min.apply(null, distance);
			i = distance.indexOf(min);
			this.inClockRange = distance[i] <= locationDistance;
			this.clockActive = this.inClockRange ? true : false;
			this.latitude = (this.markers[i].latitude + this.userPosi.latitude) / 2;
			this.longitude = (this.markers[i].longitude + this.userPosi.longitude) / 2;
			this.includePoints.push(this.userPosi, this.markers[i]);
		},
		setAddr(tip) {
			this.addr = tip;
		},
		//计算地图上两点之间的距离
		calPointerDistance(PA, PB) {
			let a = ((PA.latitude - PB.latitude) * Math.PI) / 180.0;
			let b = ((PA.longitude - PB.longitude) * Math.PI) / 180.0;
			let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(PA.latitude) * Math.cos(PB.latitude) * Math.pow(Math.sin(b / 2), 2)));
			s = s * 6378137.0;
			s = Math.round(s * 10000) / 10000;
			return s;
		},
		//打卡方法
		clockFun() {
			let that = this;
			if (that.clockActive && that.watermark) {
				that.$http
					.post({
						url: '/stu/studentAttendance/save',
						data: {
							signLongitude: that.userPosi.longitude,
							signLatitude: that.userPosi.latitude,
							signLocation: that.addr,
							signDistance: '',
							attachmentVoListStr: that.attachmentVoListStr
						}
					})
					.then(e => {
						if (e.code == 0) {
							// uni.showToast({
							// 	title: '打卡成功！',
							// 	icon: 'none'
							// });
							this.clockSuccess = true;
							setTimeout(() => {
								that.clockSuccess = false;
							}, 1200);
						} else {
							uni.showToast({
								title: e.message,
								icon: 'none'
							});
						}
					})
					.catch(e => {
						uni.showToast({
							title: e.message,
							icon: 'none'
						});
					});
			} else {
				return;
			}
		},
		//稀释打卡频率
		debounceClock(func, wait) {
			let context = this;
			// let flag = true
			if (this.timeout) clearTimeout(this.timeout);
			if (this.flag) {
				this.flag = false;
				context[func]();
			}
			this.timeout = setTimeout(() => {
				this.flag = true;
			}, wait);
		}

		// debounceClock(func, wait) {
		//         let context = this
		//         if (this.timeout) clearTimeout(this.timeout)
		//         this.timeout = setTimeout(() => {
		//             context[func]()
		//         }, wait)
		// }
	},
	computed: {
		clockText() {
			let text = this.inClockRange ? '打卡' : '超出打卡范围';
			return text;
		},
		hiddenMap() {
			let hiddenMap = uni.getStorageSync('hiddenMap');
			return hiddenMap;
		}
	},
	components: {
		commonToast
	}
};
</script>

<style lang="scss" scoped>
	.authSettingBtn{
		position: fixed;
		left: 50%;
		top:50%;
		transform:translate(-50%,-50%);
	}
.cameraBox {
	border: 1px dotted #333333;
	position: fixed;
	top: 200upx;
	left: 50%;
	transform: translateX(-50%);
	width: 600upx;
	height: 700upx;
	text-align: center;

	image {
		width: 100%;
		height: 100%;
	}

	text {
		color: #fff;
		position: absolute;
		bottom: 10upx;
		left: 20upx;
		font-weight: 600;
		text-stroke: 1upx #333;
		-webkit-text-stroke: 1upx #333;
	}
}

.cameraAction {
	width: 200upx;
	height: 200upx;
	background: linear-gradient(0deg, rgba(60, 104, 229, 1) 0%, rgba(107, 146, 255, 1) 100%);
	box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
	border-radius: 50%;
	position: fixed;
	bottom: 180upx;
	left: 25%;
	transform: translateX(-50%);
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding: 50upx 0;

	text {
		text-align: center;
		font-size: 32upx;
		font-family: PingFang SC;
		font-weight: bold;
		color: rgba(255, 255, 255, 1);
	}
}

// .camera {
// 	margin-top: 20rpx;
// 	display: block;
// 	text-align: center;
// 	font-size: 32upx;
// 	color: rgb(72, 204, 253);
// }
.map {
	width: 750upx;
}

.clockInfo {
	width: 710upx;
	height: 100upx;
	background: rgba(255, 255, 255, 1);
	border-radius: 8upx;
	position: fixed;
	top: 18upx;
	left: 50%;
	transform: translate(-50%, 0);
	display: flex;
	justify-content: space-around;
	padding: 25upx 0;
	align-items: center;

	view {
		// flex: 0 1 50%;
		text-align: center;

		&:nth-of-type(1) {
			width: 240upx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			padding-right: 10upx;
			border-right: 1upx solid #cccccc;
		}

		&:nth-of-type(2) {
			// width: 450upx;
			// white-space: nowrap;
			// overflow: hidden;
			// text-overflow: ellipsis;
		}
	}
}

.clockAction {
	width: 200upx;
	height: 200upx;
	background: linear-gradient(0deg, rgba(60, 104, 229, 1) 0%, rgba(107, 146, 255, 1) 100%);
	box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
	border-radius: 50%;
	position: fixed;
	bottom: 180upx;
	left: 75%;
	transform: translateX(-50%);
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	padding: 50upx 0;

	text {
		text-align: center;
		font-size: 32upx;
		font-family: PingFang SC;
		font-weight: bold;
		color: rgba(255, 255, 255, 1);
	}

	// font-size: 32upx;
	// font-family: PingFang SC;
	// font-weight: bold;
	// color: rgba(255, 255, 255, 1);
}

.clockGray {
	background: linear-gradient(0deg, rgba(178, 185, 202, 1) 0%, rgba(218, 221, 229, 1) 100%);
	box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
	border-radius: 50%;
}
</style>
